package com.qf.filter;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

@WebServlet("/cookieDemo1")
public class CookieDemo extends HttpServlet {


    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {

        response.setContentType("text/html;charset=utf-8");
        //1)创建Cookie对象
        //Cookie(String name, String value)
        Cookie cookie = new Cookie("username","gaoyuanyuan") ;

        Cookie cookie2 = new Cookie("time","dataTime") ;

        //2)后台提示
        System.out.println("创建cookie完毕");

        //3)将cookie信息通过响应对象携带给浏览器存储起来
        //给第一个cookie对象设置有效期
         cookie.setMaxAge(60*60*24*7);//秒 7天

         response.addCookie(cookie);
         response.addCookie(cookie2);
        /**
         * 3)原理:
         *  设置响应头:Set-Cookie: username=gaoyuanyuan  后面cookie的内容
         */

        response.getWriter().write("cookie已经携带给浏览器");

        //4)当前浏览器下一次请求服务器 时候:就会将cookie的信息添加请求头
        //request header
        //Cookie:key=value&key=value...
        //public Cookie[] getCookies()
        Cookie[] cookies = request.getCookies();
        if(cookies!=null){
            //存在
            //遍历cookie数组
            for(Cookie c : cookies){
                //通过cookie对象获取名称以及内容
                String cookieName = c.getName();
                String cookieValue = c.getValue();
                System.out.println(cookieName+"="+cookieValue);
            }
        }


    }

    protected void doPost(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        doGet(request,response);

    }
}
